<?php

namespace App\Http\Controllers\Common;

use App\Common\Constant;
use App\Http\Controllers\Controller;
use App\Model\Common;
use App\Model\Places;
use App\Model\SmsMsg;
use App\User;
use Illuminate\Http\Request;
use Psy\Util\Str;
use Symfony\Component\HttpKernel\Profiler\Profile;

class CommonController extends Controller
{
    /**
     * 上传文件接口
     * @param Request $request
     * @return \Illuminate\Http\Response
     */
    public function uploadFile(Request $request)
    {
        $data = [];
        if ($files = $request->file()) {

            $path = sprintf("/data/upload/%s/%s/%s", date('Y', time()), date('m', time()),
                date('d', time()));
            $filePath = base_path('public' . $path);
            foreach ($files as $file) {
                $fileName = \Illuminate\Support\Str::random(16) . '.' . $file->getClientOriginalExtension();
                $file->move($filePath, $fileName);
                $data[] = env('apiUrl') .'/'. $path .'/'. $fileName;
            }
            return $this->renderJson($data);
        }
        return $this->error();

    }

    /**
     * 上传多张图片
     * @param Request $request
     * @return \Illuminate\Http\Response
     */
    public function uploadFileMany(Request $request)
    {

        if ($files = $request->file('file')) {
            $data = [];
            $path = sprintf("/data/upload/%s/%s/%s", date('Y', time()), date('m', time()),
                date('d', time()));
            $filePath = base_path('public' . $path);
            foreach ($files as $file) {
                $fileName = \Illuminate\Support\Str::random(16) . '.' . $file->getClientOriginalExtension();

                $file->move($filePath, $fileName);
                $data[] = env('apiUrl') .'/'. $path .'/'. $fileName;
            }
            return $this->renderJson($data);
        }
        return $this->error();
    }


    /**
     * 上传二进制图片
     * @param Request $request
     * @return \Illuminate\Http\Response
     */
    public function uploadFileFlow(Request $request)
    {
        $base64_image_content =$request->input('file');
        if(!$base64_image_content){
            return $this->error('没有上传图片');
        }
        $data = [];
        for($i = 0; $i< count($base64_image_content); $i++){
            if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content[$i], $result)){
                $type = $result[2];
                $path = sprintf("/data/upload/%s/%s/%s", date('Y', time()), date('m', time()),
                    date('d', time()));
                $filePath = public_path($path);

                if(!is_dir($filePath))
                {
                    mkdir($filePath,0700, true);
                }
                $fileName = time().".{$type}";
                $filePath = $filePath.'/'.$fileName;
                if (file_put_contents($filePath, base64_decode(str_replace($result[1], '', $base64_image_content[$i])))){
                    $data[] = env('apiUrl') .'/' . $path .'/'. $fileName;
                }else{
                   return $this->error();
                }
            }
        }
        return $this->renderJson($data);

    }

    /**
     * 获取一级城市
     * @return \Illuminate\Http\Response
     */
    public function getParentArea(Request $request)
    {
        $area_id = $request->get('area_id');
        if ($area_id) {
            $data = Places::where('pid', $area_id)->get();
        } else {
            $data = Places::where('level', 1)->get();
        }
        return $this->renderJson($data);
    }

    /**
     * 发送短信
     * @param Request $request
     * @return \Illuminate\Http\Response
     */
    public function sendSmsCode(Request $request)
    {
        $this->validate($request, [
            'phone_number' => [
                'required',
                'regex:/^1[345789][0-9]{9}$/'
            ]
        ], [
            'phone_number.required' => '手机号不能为空',
            'phone_number.regex' => '手机号格式错误'
        ]);

        $type = request('type', 1);
        $phone = request('phone_number');
        $smsMsg = new Common();
        $res = $smsMsg->sendSmsCode($phone, $type);
        return $this->renderJson($res);
    }

    /**
     * 验证短信
     * @param Request $request
     * @return \Illuminate\Http\Response
     */
    public function validateSmsCode(Request $request)
    {
        $phone_number = $request->input('phone_number');
        $code = $request->input('sms_code');
        $time = time();

        $sms = SmsMsg::where('is_valided', 0)->where('mobile_phone', $phone_number)->orderByDesc('id')->first();

        if (!$sms) {
            return $this->fail('手机号码错误');
        } elseif (date(strtotime("+3 Minute", strtotime($sms->dead_line))) < $time) {
            return $this->success('超时，请重新发送');
        } elseif ($sms->msg_code != $code) {
            return $this->fail('验证码错误');
        }
        $sms->update(['is_valided' => 1]);
        return $this->success('验证通过');
    }

    /**
     * 消息发送接口
     * @param Request $request
     * @return \Illuminate\Http\Response
     */
    public function sendSmsMsg(Request $request)
    {
        $phone_number = $request->input('phone_number');
        $password = $request->input('password');
        $name = $request->input('name');

        $common = new Common();
        $res = $common->sendSmsMsg($name, $password, $phone_number);
        return $this->error('发送失败');
    }

    /**
     * 获取位置
     * @param Places $places
     * @param $id
     * @return \Illuminate\Http\Response
     */
    public function getCity(Places $places, $id)
    {
        return $this->renderJson($places->find($id));
    }

    public function getPlaces()
    {
        $data =  \DB::table('places')->select(['id', 'name', 'pid', 'level'])->get();

        $data = json_encode($data, true);


        $placesJson = fopen(public_path('places.json'),'w');
        fwrite($placesJson, $data);
        fclose($placesJson);
        echo 'ok';

    }

}
